<?php
namespace QnuiRingsMobile\Model;
use Think\Model;
// 软件名称：微折手机端 
// 代码日期： 2018-12-03
// 作者：杨道泉 
// 文件名：LoginModel.class.php
// 功能：用户登录操作类
class LoginModel{
	public $code;
	public function codeLogin(){
		 if(session("code")==$this->code){
			 $this->info="登陆码重复，请重新登陆";
			 return;
		 }
		 session("code",$this->code);
		 $url = 'https://oauth.taobao.com/token';
		 $postfields= array('grant_type'=>'authorization_code',
		 'client_id'=>C('APPKEY'),
		 'client_secret'=>C('APP_SECRET'),
		 'code'=>$this->code,
		 'redirect_uri'=>C("REDIRECT_URI"));
		 $post_data = '';
		 foreach($postfields as $key=>$value){
		 $post_data .="$key=".urlencode($value)."&";}
		 $ch = curl_init();
		 curl_setopt($ch, CURLOPT_URL, $url);
		 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		 curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
		 curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
		 
		 //指定post数据
		 curl_setopt($ch, CURLOPT_POST, true);

		 //添加变量
		 curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
		 $output = curl_exec($ch);
		 $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		 //echo $httpStatusCode; //400,200等http状态代码
		 //echo $output; //400,200等http状态代码
		 curl_close($ch);
		 $resp = json_decode($output);
		 $resp->taobao_user_nick = urldecode($resp->taobao_user_nick);
		 //print_r($resp);
		 if(isset($resp->error)){
			$this->info='登陆失败，请重新登陆';
			$this->info.="<br />".$resp->error_description;
			return false;
		 }else{
			// stdClass Object ( [taobao_user_nick] => zlp130 [re_expires_in] => 392381 [expires_in] => 392381 [expire_time] => 1494799200000 [r1_expires_in] => 392381 [w2_valid] => 1494334164285 [w2_expires_in] => 0 [taobao_user_id] => 44173724 [w1_expires_in] => 392381 [r1_valid] => 1494799200000 [r2_valid] => 1494591564285 [w1_valid] => 1494799200000 [r2_expires_in] => 184746 [token_type] => Bearer [refresh_token] => 6201719115ae6670fd3cd9a230fhj0feZZ3de3e6b95837744173724 [refresh_token_valid_time] => 1494799200000 [access_token] => 6201e19c2b0b843f6c6239c23ddfh5bbZZbe08b4d931a4544173724 )

			
			session("VISITOR_ID",$resp->taobao_user_id);
			session("VISITOR_NICK",$resp->taobao_user_nick);
			session("VISITOR_SUB_NICK",$resp->sub_taobao_user_nick);
			session("refresh_token",$resp->refresh_token);
			session("TOP_SESSION",$resp->access_token);
			session("time",date("G:i:s"));
			session("expire_time",$resp->expire_time); //操作到期时间
			session("w2_valid",$resp->w2_valid);
			session("r1_valid",$resp->r1_valid);
			session("w1_valid",$resp->w1_valid);
			session("refresh_token_valid_time",$resp->refresh_token_valid_time);
			session("TIMESTEMP",time());
			
			return true;
		 }
	}
}